package com.sihai.ehr.web.action.exam;

import java.net.Proxy.Type;
import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.EmployeeinfoWork;
import com.sihai.ehr.model.biz.ExamQualCoerceSet;
import com.sihai.ehr.model.biz.ExamQualDistSet;
import com.sihai.ehr.model.sys.DispersionPatternEnum;
import com.sihai.ehr.model.sys.ExaminePeriodEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.service.ExamQualSetService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.action.invite.InviteFormAction;

/**
 * 考核强制分布设定
 * 
 * @author Henry
 * 
 */
@Results({ @Result(name = "qualset", location = "exam_qualset.jsp"),
		@Result(name = "qualset_list", location = "exam_qualset_list.jsp"),
		@Result(name = "qualset_add", location = "exam_qualset_add.jsp"),
		@Result(name = "main", location = "exam_qualset_main.jsp"),
		@Result(name = "qualset_dist", location = "exam_qual_score_dist.jsp") })
public class ExamQualSetAction extends EHRAction {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 7204414972672241268L;
	Log log = LogFactory.getLog(InviteFormAction.class);

	@BeanInject
	private ExamQualSetService examQualSetService;
	@BeanInject
	private EmployeeService employeeService;
	@BeanInject
	private OrganizationService organizationService;

	/** 移出的ID集合 */
	private String ids;
	/** 页面标题 */
	private String title;
	/** 分布类型 */
	private String dispatchType;
	/** 周期类型 */
	private ExaminePeriodEnum periodType;
	/** 部门总人数 */
	private Long totalCount;
	private float percentage;
	/** 考核强制分布设置对象 */
	private ExamQualDistSet examQualDistSet;
	/** 考核强制分布设定对象 */
	private ExamQualCoerceSet examQualCoerceSet;
	/** 考核强制分布集合 */
	private LimitedList<ExamQualCoerceSet> examQualCoerceSets;

	private static DecimalFormat decimalFormat = new DecimalFormat("#.#");

	/** 考核强制分布控制入口 */
	@Action("/exam/qualset_main")
	@Override
	public String execute() throws Exception {
		listAction = "/exam/qualset.xhtml";
		listTitle = "强制性分布设定";
		return "main";
	}

	/** 考核强制分布列表 */
	@Action("/exam/qualset")
	public String list() throws Exception {
		// 加载tab项目
		listAction = "/exam/qualset_list.xhtml";
		try {
			examQualDistSet = examQualSetService
					.getExamQualDistSet(organizationId,
							periodType == null ? ExaminePeriodEnum.monthly
									: periodType);
			if (examQualDistSet == null) {
				examQualDistSet = new ExamQualDistSet();
				examQualDistSet.setType(DispersionPatternEnum.percentage);
			}
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.equals("【强制分布类型发生异常】【异常原因：" + e.getMessage() + "】");
			}
		}
		return "qualset";
	}

	@Action("/exam/qualset_list")
	public String queryQualSetList() throws Exception {
		if (getParameter("type") == null) {
			if (log.isErrorEnabled()) {
				log.equals("【强制分布类型参数为空】");
			}
		}
		try {
			DispersionPatternEnum lPatternEnum = DispersionPatternEnum
					.valueOf(getParameter("type"));
			if (lPatternEnum == null) {
				if (log.isErrorEnabled()) {
					log.equals("【强制分布类型参数为空】");
				}
			}
			totalCount = examQualSetService
					.getTotalCountByOrganizationIdAndPeriodType(organizationId,
							periodType, true);
			examQualCoerceSets = examQualSetService.searchExamQualCoerceSets(
					organizationId, lPatternEnum, periodType, createLimit(),
					createSorter().desc("scoreStart"));
			/* 分页 */
			this.paging(examQualCoerceSets);
			/* 设置翻页action */
			this.setPageUrl("exam/qualset_list.xhtml");
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【获取强制分布异常】【错误原因:" + e.getMessage() + "】");
			}
		}
		return "qualset_list";
	}

	/**
	 * 查询定性分布
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qualset_dist")
	public String queryQualSetListFromScore() throws Exception {
		try {
			examQualCoerceSets = examQualSetService.searchExamQualCoerceSets(
					organizationId, periodType, null, null);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【获取强制分布异常】【错误原因:" + e.getMessage() + "】");
			}
		}
		return "qualset_dist";
	}

	@Action(value = "/exam/post_qualdistset", results = { @Result(name = "success", type = "plainText") })
	public String postQualDistSet() throws Exception {
		if (getParameter("type") == null) {
			if (log.isErrorEnabled()) {
				log.equals("【强制分布类型参数为空】");
			}
			return ERROR;
		}
		try {
			DispersionPatternEnum lPatternEnum = DispersionPatternEnum
					.valueOf(getParameter("type"));
			if (lPatternEnum == null) {
				if (log.isErrorEnabled()) {
					log.equals("【强制分布类型参数为空】");
				}
				return ERROR;
			}
			// 清出该部门的强制分页设定数据
			examQualSetService.deleteExamQualCoerceSets(organizationId,
					periodType);

			// 设定部门强制分页设定
			examQualDistSet = examQualSetService.getExamQualDistSet(
					organizationId, periodType);
			if (examQualDistSet == null) {
				examQualDistSet = new ExamQualDistSet();
				examQualDistSet.setOrganization(organizationService
						.get(organizationId));
			}
			examQualDistSet.setType(lPatternEnum);
			examQualDistSet.setPeriodType(periodType);
			examQualSetService.saveExamQualDistSet(examQualDistSet);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【保存或修改强制分布设置发生异常】【异常原因：" + e.getMessage() + "】");
			}
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 添加考核强制分布设置请求
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qualset_add")
	public String handleQualSet() throws Exception {
		float currentPercent = 0;
		// 检测是否是修改申请
		if (getParameter("qualsetId") != null) {
			title = "修改";
			try {
				examQualCoerceSet = examQualSetService
						.getExamQualCoerceSet(Long
								.parseLong(getParameter("qualsetId")));
				if (dispatchType != null
						&& dispatchType
								.equalsIgnoreCase(DispersionPatternEnum.percentage
										.toString())) {
					currentPercent = 100 * examQualCoerceSet.getPercentage();
				}
				if (examQualCoerceSet != null) {
					organizationId = examQualCoerceSet.getOrganization()
							.getId();
				}
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error("【读取强制分布设置发生异常】【异常原因：" + e.getMessage() + "】");
				}
				return ERROR;
			}
		} else {
			title = "添加 ";
			examQualCoerceSet = new ExamQualCoerceSet();
			Organization organization = new Organization();
			organization.setId(organizationId);
			examQualCoerceSet.setOrganization(organization);
			examQualCoerceSet.setType(DispersionPatternEnum
					.valueOf(dispatchType));
			examQualCoerceSet.setPeriodType(periodType);
		}
		// 查询已经设置的百分比
		Float d = examQualSetService.getQualCoerceTotalPercentageByOrgId(
				organizationId, examQualCoerceSet.getPeriodType());
		percentage = 100f + currentPercent
				- (d == null ? 0f : d.floatValue() * 100);
		percentage = Float.parseFloat(decimalFormat.format(percentage));
		return "qualset_add";
	}

	@Action(value = "/exam/validate_score", results = { @Result(name = "success", type = "plainText") })
	public String validateInputScore() throws Exception {
		if (getParameter("st") == null || getParameter("se") == null) {
			return ERROR;
		}
		Long id = -1L;
		if (getParameter("i") != null) {
			id = Long.parseLong(getParameter("i"));
		}
		try {
			boolean isExist = examQualSetService.checkScoreAreaExist(
					organizationId,
					Float.parseFloat(getParameter("st").toString()),
					Float.parseFloat(getParameter("se").toString()),
					periodType, id);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write(
					"{\"availability\":" + (isExist ? false : true) + "}");
			response.getWriter().flush();
			response.getWriter().close();
			return SUCCESS;
		} catch (Exception e) {
			return ERROR;
		}

	}

	/** 考核强制分布添加 */
	@Action("/exam/post_qualset")
	public String postQualSet() throws Exception {

		if (examQualCoerceSet == null) {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】");
				return ERROR;
			}
		}
		try {

			// 检测强制分页tab设置是否设置过
			ExamQualDistSet distSet = examQualSetService.getExamQualDistSet(
					examQualCoerceSet.getOrganization().getId(),
					examQualCoerceSet.getPeriodType());
			if (distSet == null) {
				distSet = new ExamQualDistSet();
				distSet.setOrganization(examQualCoerceSet.getOrganization());
				distSet.setType(examQualCoerceSet.getType());
				distSet.setPeriodType(examQualCoerceSet.getPeriodType());
				examQualSetService.saveExamQualDistSet(distSet);
			}

			if (examQualCoerceSet.getId() != null
					&& examQualCoerceSet.getId() > 0) {
				examQualSetService
						.deleteExamQualCoerceSetsById(examQualCoerceSet.getId());
				examQualCoerceSet.setId(null);
			}

			Long staffCount = examQualSetService
					.getTotalCountByOrganizationIdAndPeriodType(
							examQualCoerceSet.getOrganization().getId(),
							examQualCoerceSet.getPeriodType(), true);
			// 百分比计算出人数
			if (examQualCoerceSet.getType() == DispersionPatternEnum.percentage) {
				examQualCoerceSet.setPercentage(examQualCoerceSet
						.getPercentage() / 100);
				examQualCoerceSet.setNumber((int) Math
						.floor((double) examQualCoerceSet.getPercentage()
								* staffCount));
			} else if (examQualCoerceSet.getType() == DispersionPatternEnum.custom_field) {
				examQualCoerceSet
						.setPercentage(staffCount != 0 ? (float) examQualCoerceSet
								.getNumber() / staffCount
								: 0);
			}
			// 添加或修改数据
			examQualSetService.saveExamQualCoerceSet(examQualCoerceSet);
			// if(examQualCoerceSet.getType() ==
			// DispersionPatternEnum.percentage){
			// //调整人数
			// List<ExamQualCoerceSet> coerceSets = examQualSetService
			// .searchExamQualCoerceSets(examQualCoerceSet
			// .getOrganization().getId(), null, null);
			// Float hasSetPercentage = 0f;
			// int hasSetNubmer = 0;
			// for (ExamQualCoerceSet coerceSet : coerceSets) {
			// hasSetPercentage += coerceSet.getPercentage();
			// hasSetNubmer += coerceSet.getNumber();
			// }
			// if(hasSetPercentage >= 1 && hasSetNubmer < staffCount){
			// ExamQualCoerceSet vCoerceSet = coerceSets.get(coerceSets.size() /
			// 2 + coerceSets.size() % 2 );
			// vCoerceSet.setNumber(vCoerceSet.getNumber() +
			// (Integer.parseInt(staffCount.toString()) - hasSetNubmer));
			// examQualSetService.saveExamQualCoerceSet(vCoerceSet);
			// }
			// }
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【保存或修改强制分布设置发生异常】【异常原因：" + e.getMessage() + "】");
			}
			return ERROR;
		}

		return "qualset_add";
	}

	/**
	 * 移动考核强制分布设置
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/exam/qualset_delete", results = { @Result(name = "success", type = "plainText") })
	public String removeInviteByIds() throws Exception {
		if (ids == null || ids.isEmpty()) {
			if (log.isErrorEnabled()) {
				log.error("【移除考核强制分布ID集合参数异常】");
			}
			return ERROR;
		}
		try {
			examQualSetService.removeExamQualCoerceSets(ids);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【移除考核强制分布发生异常】");
			}
			return ERROR;
		}
		return SUCCESS;
	}

	/*************************************
	 * Preperty gram.
	 * 
	 ************************************/

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDispatchType() {
		return dispatchType;
	}

	public void setDispatchType(String dispatchType) {
		this.dispatchType = dispatchType;
	}

	public ExaminePeriodEnum getPeriodType() {
		return periodType;
	}

	public void setPeriodType(ExaminePeriodEnum periodType) {
		this.periodType = periodType;
	}

	public Long getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(Long totalCount) {
		this.totalCount = totalCount;
	}

	public float getPercentage() {
		return percentage;
	}

	public void setPercentage(float percentage) {
		this.percentage = percentage;
	}

	public ExamQualDistSet getExamQualDistSet() {
		return examQualDistSet;
	}

	public void setExamQualDistSet(ExamQualDistSet examQualDistSet) {
		this.examQualDistSet = examQualDistSet;
	}

	public ExamQualCoerceSet getExamQualCoerceSet() {
		return examQualCoerceSet;
	}

	public void setExamQualCoerceSet(ExamQualCoerceSet examQualCoerceSet) {
		this.examQualCoerceSet = examQualCoerceSet;
	}

	public LimitedList<ExamQualCoerceSet> getExamQualCoerceSets() {
		return examQualCoerceSets;
	}

	public void setExamQualCoerceSets(
			LimitedList<ExamQualCoerceSet> examQualCoerceSets) {
		this.examQualCoerceSets = examQualCoerceSets;
	}
}
